package com.qidian.buy.cms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qidian.buy.entity.ContentCategory;
import com.qidian.buy.cms.mapper.ContentCategoryMapper;
import com.qidian.buy.cms.service.IContentCategoryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qidian.buy.util.pojo.BuyResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * <p>
 * 内容分类 服务实现类
 * </p>
 *
 * @author 戴着假发的程序员
 * @since 2023-07-05
 */
@Service
public class ContentCategoryServiceImpl extends ServiceImpl<ContentCategoryMapper, ContentCategory> implements IContentCategoryService {
    @Autowired
    private ContentCategoryMapper catMapper;
    @Override
    public BuyResult queryByParentId(Long parentId) {
        QueryWrapper<ContentCategory> wrapper = new QueryWrapper<>();
        wrapper.eq(parentId!=null,"parent_id",parentId);
        return BuyResult.ok(catMapper.selectList(wrapper));
    }

    @Override
    public BuyResult saveCat(ContentCategory cat) {
        System.out.println(cat);
        // 补全数据  前端只会提交parentId和name
        cat.setStatus(1);
        cat.setSortOrder(1);
        cat.setIsParent(false);// 新建的类别肯定是叶子节点
        cat.setCreated(new Date());
        cat.setUpdated(new Date());
        if(catMapper.insert(cat)==1){
            // 判断父节点是否之前就是父节点
            ContentCategory parentCat = catMapper.selectById(cat.getParentId());
            if(!parentCat.getIsParent()) {
                parentCat.setIsParent(true);
                catMapper.updateById(parentCat);
            }
        }
        return BuyResult.ok();
    }

    @Override
    public BuyResult queryById(Long catId) {
        return BuyResult.ok(catMapper.selectById(catId));
    }

    @Override
    public BuyResult updateCat(ContentCategory cat) {
        cat.setUpdated(new Date());// 补全更新时间
        return BuyResult.ok(catMapper.updateById(cat));
    }

    @Override
    public BuyResult deleteCat(Long catId) {
        // 查询要删除的节点
        ContentCategory cat = catMapper.selectById(catId);
        if(catMapper.deleteById(catId)==1){
            // 查询父节点的子节点数量
            QueryWrapper wrapper = new QueryWrapper();
            wrapper.eq("parent_id",cat.getParentId());
            if(catMapper.selectCount(wrapper)==0){
                // 没有子节点了
                ContentCategory parentCat = new ContentCategory();
                parentCat.setId(cat.getParentId());
                parentCat.setIsParent(false);
                catMapper.updateById(parentCat);
            }
        }
        return BuyResult.ok();
    }
}
